//
//  JOOauthController.m
//  新浪微博模拟
//
//  Created by song on 15/9/14.
//  Copyright (c) 2015年 song. All rights reserved.
//

#import "JOOauthController.h"
#import "AFNetworking.h"
#import "JOAccount.h"
@interface JOOauthController ()<UIWebViewDelegate>



@end


@implementation JOOauthController



-(void)viewDidLoad
{
    [super viewDidLoad];
    UIWebView *webView = [[UIWebView alloc] init];
    webView.frame = self.view.bounds;
    webView.delegate = self;
    [self.view addSubview:webView];
    
    NSURL *url= [NSURL URLWithString:@"https://api.weibo.com/oauth2/authorize?client_id=2783000706&redirect_uri=http://www.bing.com"];
    NSURLRequest *request =[NSURLRequest requestWithURL:url];
    [webView loadRequest:request];
}


-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    NSLog(@"----%@" ,request.URL);
    NSString *url = [request.URL absoluteString];
    NSRange rang = [url rangeOfString:@"code"];
    if(rang.location !=NSNotFound)
    {
        int pos = rang.location + rang.length+1;
        NSString *code = [url substringFromIndex:pos];
        [self getAccessToken:code];
        
    }
    return true;
}


-(void)getAccessToken:(NSString *)code
{
    AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
    

    mgr.responseSerializer = [AFJSONResponseSerializer serializer];
    NSMutableDictionary *params =[NSMutableDictionary dictionary];
    params[@"client_id"]=@"2783000706";
    params[@"client_secret"]=@"7ee8845d26b6ed60dad91d916923c29f";
    params[@"grant_type"]=@"authorization_code";
    params[@"code"]=code;
    params[@"redirect_uri"]=@"http://www.bing.com";
    
    [mgr POST:@"https://api.weibo.com/oauth2/access_token" parameters:params success:^(AFHTTPRequestOperation * operation, id response) {
        NSLog(@"请求成功 --%@",response);
        JOAccount *account =[JOAccount accountWithDic:response];
        NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES) lastObject];
        NSString *filepath =[path stringByAppendingString:@"account.data"];
        NSLog(@"---file path %@",filepath);
        [NSKeyedArchiver archiveRootObject:account toFile:filepath];
        
        
    } failure:^(AFHTTPRequestOperation * operation, NSError * error) {
        NSLog(@"请求错误 ----- %@" , error);
    }];
    
}


@end
